<?php

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class Article extends Model
{
    //软删除
    use SoftDelete;

    //关联评论
    public function comments(){
        return $this->hasMany('Comment');
    }

    //文章添加
    public function add($data)
    {
        $validate = new \app\common\validate\Article();
        if (!$validate->scene('add')->check($data)) {
            return $validate->getError();
        }
        $result = $this->allowField(true)->save($data);
        if ($result) {
            return 1;
        } else {
            return "文章添加失败！";
        }
    }

    //文章列表
    public function cateList(){
        return $this->belongsTo('Cate');
    }

    //是否推进
    public function top($data){
        $articles = $this->find($data['id']);
        $articles->is_top = $data['is_top'];
        $result = $articles->save();
        if ($result){
            return 1;
        }else{
            return "操作失败";
        }

    }

    //编辑
    public function edit($data){
        $validate = new \app\common\validate\Article();
        if (!$validate->scene('edit')->check($data)){
            return $validate->getError();
        }
        $article = $this->find($data['id']);
        $article['title'] = $data['title'];
        $article['tags'] = $data['tags'];
        $article['is_top'] = $data['is_top'];
        $article['cate_id'] = $data['cate_id'];
        $article['desc'] = $data['desc'];
        $article['content'] = $data['content'];
        $result = $article->save();
        if ($result){
            return 1;
        }else{
            return "编辑失败";
        }
    }

    //搜索文章
    public function searchTitleAttr($query, $value, $data)
    {
        $query->where('title','like', $value.'%');
    }
}
